package com.whisperly.echotalk.other;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.LocaleList;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.appsflyer.AppsFlyerLib;
import com.appsflyer.attribution.AppsFlyerRequestListener;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdValue;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.VideoOptions;
import com.google.android.gms.ads.nativead.MediaView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdOptions;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.whisperly.echotalk.account.Account;
import com.whisperly.echotalk.bllmodel.BaseResponse;
import com.whisperly.echotalk.bllmodel.ClientClear;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.bllmodel.SignUp;
import com.whisperly.echotalk.bllmodel.UpdateInfo;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.schemas.Login;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.schemas.VersionUpgrade;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.BaseURL;
import com.whisperly.echotalk.starryb.utils.GlobalData;
import com.whisperly.echotalk.starryb.utils.Mutual;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

public class Settings extends AppCompatActivity {
    private LinearLayout page_row1, page_row2, page_row3, page_row4, page_row5, page_row6,page_row_language;
    private Toast currentToast;
    private LinearLayout content, signIn;
    private TextView txtUserName, txtUserID, txtLastTime, tvPrivacyPolicy, tvTermsConditions;
    private UserWithChat user = new UserWithChat();
    private TextView clock_day,integral;
    private static final String LOG_TAG = "Settings";
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    private void syncSignUpData() {
        if (GlobalData.objectId != null) {
            NetworkUtils.getByUserId(GlobalData.objectId, new BlinkCallback() {
                @Override
                public void onSuccess(ResultBody<?> response) {
                    runOnUiThread(() -> {
                        try {
                            if (response.getCode() == 200) {
                                BaseResponse<?> data1 = (BaseResponse<?>) response.getData();
                                SignUp data2 = (SignUp) data1.getData();
                                if (data2 != null) {
                                    // 更新全局数据
                                    GlobalData.setSignup(data2);

                                    // 更新UI显示
                                    String singUpValue = data2.getSingUp() == null ? "0" :
                                            data2.getSingUp().toString();
                                    String integralValue = data2.getIntegralValue() == null ? "0" :
                                            data2.getIntegralValue().toString();

                                    clock_day.setText(singUpValue);
                                    integral.setText(integralValue);
                                }
                            }
                        } catch (Exception e) {
                            Log.e("Settings", "Error updating sign up data", e);
                        }
                    });
                }

                @Override
                public void onFailure(Throwable throwable) {
                    Log.e("Settings", "Error syncing sign up data", throwable);
                }
            });
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.x_settings);
        AppsManager.addActivity(this);
        content = findViewById(R.id.content);
        txtUserName = findViewById(R.id.txtUserName);
        txtUserID = findViewById(R.id.txtUserID);
        txtLastTime = findViewById(R.id.txtLastTime);
        clock_day = findViewById(R.id.clock_day);
        integral = findViewById(R.id.integral);
        signIn = findViewById(R.id.signIn);
        page_row_language = findViewById(R.id.page_row_language);

        String singUpValue = GlobalData.getSignup().getSingUp() == null ? "0" : GlobalData.getSignup().getSingUp().toString();
        String integralValue = GlobalData.getSignup().getIntegralValue() == null ? "0" : GlobalData.getSignup().getIntegralValue().toString();
        clock_day.setText(singUpValue);
        integral.setText(integralValue);
        if (GlobalData.getUsername() != null && !GlobalData.getUsername().isEmpty()) {
            content.setVisibility(View.VISIBLE);
            signIn.setVisibility(View.VISIBLE);
            user = GlobalData.getUser();
            txtUserName.setText(user.getName());
            txtUserID.setText(String.valueOf(user.getLoginId()));
            txtLastTime.setText(user.getLoginTime());
        } else {
            content.setVisibility(View.GONE);
            signIn.setVisibility(View.GONE);
        }

        page_row1 = findViewById(R.id.page_row1);
        page_row1.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.this, Account.class);
            startActivity(intent);
        });
        page_row2 = findViewById(R.id.page_row2);
        page_row2.setOnClickListener(v -> {
            if ("".equals(GlobalData.getUsername())) {
                showRegistrationAlertDialog();
            } else {
                Intent intent = new Intent(Settings.this, Records.class);
                startActivity(intent);
            }
        });
        page_row3 = findViewById(R.id.page_row3);
        page_row3.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.this, ClientClear.class);
            startActivity(intent);
        });

        page_row4 = findViewById(R.id.page_row4);
        page_row4.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.this, FeedBack.class);
            startActivity(intent);
        });
        page_row5 = findViewById(R.id.page_row5);
        page_row5.setOnClickListener(v -> {
            if (isEnglishLanguage()){
                Intent intent = new Intent(Settings.this, VersionUpgrade.class);
                intent.putExtra("isEnglish", true);
                startActivity(intent);
            }else {
                Intent intent = new Intent(Settings.this, VersionUpgrade.class);
                intent.putExtra("isEnglish", false);
                startActivity(intent);
            }

        });
        page_row6 = findViewById(R.id.page_row6);
        page_row6.setOnClickListener(v -> {
            Intent intent = new Intent(this, About.class);
            startActivity(intent);
        });

        page_row_language.setOnClickListener(v -> showChangeLanguageDialog());

        tvPrivacyPolicy = findViewById(R.id.tv_privacy_policy);

        tvTermsConditions = findViewById(R.id.tv_terms_conditions);

        tvPrivacyPolicy.setText(Html.fromHtml(getString(R.string.Privacy), Html.FROM_HTML_MODE_LEGACY));
        tvTermsConditions.setText(Html.fromHtml(getString(R.string.Terms_and_Conditions), Html.FROM_HTML_MODE_LEGACY));


        tvPrivacyPolicy.setOnClickListener(v -> {
            showPrivacyPolicy();
        });

        tvTermsConditions.setOnClickListener(v -> {
            showTermsConditions();
        });

        // 初始化时先从本地获取数据
        updateUIWithLocalData();

        // 然后立即同步服务器数据
        syncSignUpData();

        showAdDialogIfNeeded();

    }

    private void showAdDialogIfNeeded() {
        // 添加一些条件来判断是否应该显示广告
        // 比如：用户访问次数、时间间隔等
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        long lastAdTime = prefs.getLong("last_ad_time", 0);
        long currentTime = System.currentTimeMillis();

        // 至少间隔5分钟才显示下一个广告
        if (currentTime - lastAdTime < 5 * 60 * 1000) {
            return;
        }

        showCompliantAdDialog();
    }

    private void updateUIWithLocalData() {
        String singUpValue = GlobalData.getSignup().getSingUp() == null ? "0" :
                GlobalData.getSignup().getSingUp().toString();
        String integralValue = GlobalData.getSignup().getIntegralValue() == null ? "0" :
                GlobalData.getSignup().getIntegralValue().toString();

        clock_day.setText(singUpValue);
        integral.setText(integralValue);

        if (GlobalData.getUsername() != null && !GlobalData.getUsername().isEmpty()) {
            content.setVisibility(View.VISIBLE);
            signIn.setVisibility(View.VISIBLE);
            user = GlobalData.getUser();
            txtUserName.setText(user.getName());
            txtUserID.setText(String.valueOf(user.getLoginId()));
            txtLastTime.setText(user.getLoginTime());
        } else {
            content.setVisibility(View.GONE);
            signIn.setVisibility(View.GONE);
        }
    }

    // 添加一个广播接收器来接收签到成功的通知
    private final BroadcastReceiver signUpUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("com.whisperly.echotalk.SIGNUP_UPDATE".equals(intent.getAction())) {
                syncSignUpData();
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        // 注册广播接收器
        IntentFilter filter = new IntentFilter("com.whisperly.echotalk.SIGNUP_UPDATE");
        LocalBroadcastManager.getInstance(this).registerReceiver(signUpUpdateReceiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 取消注册广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(signUpUpdateReceiver);
    }

    private void showCompliantAdDialog() {
        Dialog dialog = new Dialog(this, R.style.CustomDialogStyle);
        dialog.setContentView(R.layout.dialog_ad);
        dialog.setCancelable(true); // 允许用户取消

        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            dialog.getWindow().setLayout(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
        }

        NativeAdView adView = dialog.findViewById(R.id.native_ad_view);
        MediaView mediaView = adView.findViewById(R.id.ad_media);
        TextView headlineView = adView.findViewById(R.id.ad_headline);
        TextView bodyView = adView.findViewById(R.id.ad_body);
        ImageView appIconView = adView.findViewById(R.id.ad_app_icon);
        Button ctaButton = adView.findViewById(R.id.ad_call_to_action);
        TextView adLabel = dialog.findViewById(R.id.ad_label);
        ImageView closeButton = dialog.findViewById(R.id.close_button);

        // 设置广告标识
        if (adLabel != null) {
            adLabel.setVisibility(View.VISIBLE);
        }

        // 设置关闭按钮（可选）
        if (closeButton != null) {
            closeButton.setVisibility(View.VISIBLE);
            closeButton.setOnClickListener(v -> {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
        }

        VideoOptions videoOptions = new VideoOptions.Builder()
                .setStartMuted(true)
                .build();

        NativeAdOptions adOptions = new NativeAdOptions.Builder()
                .setVideoOptions(videoOptions)
                .build();

        AdLoader adLoader = new AdLoader.Builder(this, BaseURL.AD_UNIT_ID_NATIVE)
                .forNativeAd(nativeAd -> {
                    if (isFinishing() || isDestroyed()) {
                        nativeAd.destroy();
                        return;
                    }

                    try {
                        // 正确绑定所有广告组件
                        if (mediaView != null) {
                            adView.setMediaView(mediaView);
                        }

                        if (headlineView != null && nativeAd.getHeadline() != null) {
                            adView.setHeadlineView(headlineView);
                            headlineView.setText(nativeAd.getHeadline());
                        }

                        if (bodyView != null && nativeAd.getBody() != null) {
                            adView.setBodyView(bodyView);
                            bodyView.setText(nativeAd.getBody());
                        }

                        if (appIconView != null && nativeAd.getIcon() != null) {
                            adView.setIconView(appIconView);
                            appIconView.setImageDrawable(nativeAd.getIcon().getDrawable());
                        }

                        if (ctaButton != null && nativeAd.getCallToAction() != null) {
                            adView.setCallToActionView(ctaButton);
                            ctaButton.setText(nativeAd.getCallToAction());
                        }

                        // 设置广告对象到AdView
                        adView.setNativeAd(nativeAd);

                        // 记录广告显示时间
                        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                        prefs.edit().putLong("last_ad_time", System.currentTimeMillis()).apply();

                        // 显示对话框
                        if (!isFinishing() && !isDestroyed()) {
                            dialog.show();
                        }

                        // 记录广告展示事件（用于分析）
                        logAdImpressionEvent();

                    } catch (Exception e) {
                        Log.e("AdDialog", "Error setting up native ad", e);
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                })
                .withAdListener(new AdListener() {
                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError adError) {
                        Log.e("AdDialog", "Ad failed to load: " + adError.getMessage());
                        // 不要强制关闭dialog，让用户自然离开
                    }

                    @Override
                    public void onAdClicked() {
                        super.onAdClicked();
                        // 记录广告点击事件
                        logAdClickEvent();
                    }

                    @Override
                    public void onAdClosed() {
                        super.onAdClosed();
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                })
                .withNativeAdOptions(adOptions)
                .build();

        // 加载广告
        adLoader.loadAd(new AdRequest.Builder().build());
    }

    private void logAdImpressionEvent() {
        try {
            Map<String, Object> eventValues = new HashMap<>();
            eventValues.put("ad_type", "native");
            eventValues.put("ad_placement", "settings_page");

            AppsFlyerLib.getInstance().logEvent(getApplicationContext(),
                    "ad_impression", eventValues, new AppsFlyerRequestListener() {
                        @Override
                        public void onSuccess() {
                            Log.d(LOG_TAG, "Ad impression event sent successfully");
                        }

                        @Override
                        public void onError(int i, @NonNull String s) {
                            Log.d(LOG_TAG, "Ad impression event failed: " + s);
                        }
                    });
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error logging ad impression event", e);
        }
    }

    private void logAdClickEvent() {
        try {
            Map<String, Object> eventValues = new HashMap<>();
            eventValues.put("ad_type", "native");
            eventValues.put("ad_placement", "settings_page");

            AppsFlyerLib.getInstance().logEvent(getApplicationContext(),
                    "ad_click", eventValues, new AppsFlyerRequestListener() {
                        @Override
                        public void onSuccess() {
                            Log.d(LOG_TAG, "Ad click event sent successfully");
                        }

                        @Override
                        public void onError(int i, @NonNull String s) {
                            Log.d(LOG_TAG, "Ad click event failed: " + s);
                        }
                    });
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error logging ad click event", e);
        }
    }

    private void showUpdateDialog(UpdateInfo updateInfo) {
        String updateMessage = updateInfo.getUpdateMessage().replace("\\n", "\n");
        new AlertDialog.Builder(this)
                .setTitle(R.string.update_notice)
                .setMessage(updateMessage)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(R.drawable.tip)
                .show();
    }

    private String getCurrentAppVersion() {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "-1"; // 返回-1表示获取版本号失败
        }
    }

    private boolean isEnglishLanguage() {
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        return language.equals("en");
    }

    private void showRegistrationAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.login_is_required)
                .setMessage(R.string.login_is_required_message)
                .setPositiveButton(R.string.login, (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(this, Login.class);
                    startActivity(intent);
                    AppsManager.finishAll();
                }).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).setCancelable(false)
                .show();
    }

    private void showPrivacyPolicy() {
        Intent intent = new Intent(this, Mutual.class);
        intent.putExtra("str1", BaseURL.PRIVACY_POLICY);
        intent.putExtra("str2", "Privacy Policy");
        startActivity(intent);
    }

    private void showTermsConditions() {
        Intent intent = new Intent(this, Mutual.class);
        intent.putExtra("str1", BaseURL.TERMS_CONDITIONS);
        intent.putExtra("str2", "User Agreement");
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 获取最新的签到数据
        syncSignUpData();
    }

    public void changeLanguage(String languageCode) {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putString("language", languageCode).apply();

        Intent i = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage(getBaseContext().getPackageName());
        Objects.requireNonNull(i).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }

    public void showChangeLanguageDialog() {
        final String[] languageItems = {"English", "中文"};
        final String[] languageCodes = {"en", "zh"};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.language_settings)
                .setItems(languageItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        changeLanguage(languageCodes[which]);
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
